import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/guess")
public class GuessServlet extends HttpServlet {
    @Override
    public void init() throws ServletException {
        int randomNumber = (int)(Math.random() * 100) + 1;
        ServletContext context = getServletContext();
        context.setAttribute("randomNumber", randomNumber);
        System.out.println(randomNumber);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应的字符编码为 UTF-8
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");

        // 方法 1：重定向到 guess.html
        response.sendRedirect("guess.html");

        // 或者方法 2：直接输出表单
        /*
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head><title>Guess Number</title></head>");
        out.println("<body>");
        out.println("<h1>猜数字游戏</h1>");
        out.println("<form action='guess' method='post'>");
        out.println("<label for='guess'>请输入你的猜测（1-100）：</label>");
        out.println("<input type='number' id='guess' name='guess' min='1' max='100' required>");
        out.println("<button type='submit'>提交</button>");
        out.println("</form>");
        out.println("</body>");
        out.println("</html>");
        */
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求的字符编码为 UTF-8
        request.setCharacterEncoding("UTF-8");

        // 设置响应的字符编码为 UTF-8
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");

        // 处理逻辑
        int guess = Integer.parseInt(request.getParameter("guess"));
        int randomNumber = (int) getServletContext().getAttribute("randomNumber");

        String message;
        if (guess == randomNumber) {
            message = "恭喜你！你猜对了！正确答案是：" + randomNumber;
        } else if (guess > randomNumber) {
            message = "太高了!";
        } else {
            message = "太低了!";
        }

        request.setAttribute("message", message);
        request.getRequestDispatcher("/result.jsp").forward(request, response);
    }
}